package com.fengpanlong.service;

import java.util.ArrayList;
import java.util.List;

import com.fengpanlong.dao.EmployeeDao;
import com.fengpanlong.dao.EmployeeProjectDao;
import com.fengpanlong.dao.MessageDao;
import com.fengpanlong.dao.ProjectDao;
import com.fengpanlong.entity.Employee;
import com.fengpanlong.entity.EmployeeProject;
import com.fengpanlong.entity.Message;
import com.fengpanlong.entity.Project;
import com.fengpanlong.util.StringUtil;
import com.fengpanlong.util.exception.ServiceException;

public class ProjectService {

	/**
	 * 保存新项目
	 * @param title 项目名称
	 * @param desc 姓名描述
	 * @param managerName 项目的创建者名字
	 * @param employeeNames 成语名字
	 * @throws ServiceException
	 */
	public static void saveNewProject(String title, String desc,
			String managerName, String employeeNames) throws ServiceException {
		if(StringUtil.isEmpty(title)) {
			throw new ServiceException("标题不能为空！");
		} else if(StringUtil.isEmpty(managerName)){
			throw new ServiceException("负责人不能为空！");
		} else if(StringUtil.isEmpty(employeeNames)){ 
			throw new ServiceException("项目成员不能为空！");
		} else {
			ProjectDao pd = new ProjectDao();
			Project p = pd.findByName(title);
			if( p != null) {
				throw new ServiceException("项目名已存在！");
			} 
			String id = StringUtil.getId();
			String createtime = StringUtil.formateTime();
			List<String> employeeNamesList = StringUtil.parseEmployeesToString(employeeNames);
			Project project = new Project();
			project.setId(id);
			project.setDesc(desc);
			project.setName(title);
			project.setCreatetime(createtime);
			EmployeeDao ed = new EmployeeDao();
			Employee manager = ed.findByName(managerName);
			List<Employee> employeeList = ed.findByList(employeeNamesList);
			pd.saveProject(project, manager, employeeList);
		}
			
	}
	/**
	 * 通过项目名称查找项目
	 * @param name 项目名称
	 * @return 项目对象
	 */
	public static Project findProjectByName(String name) {
		ProjectDao pd = new ProjectDao();
		return pd.findByName(name);
	}
	/**
	 * 通过项目id和用户id得到关系对象
	 * @param employeeId  用户id
	 * @param projectId 项目id
	 * @return 关系对象
	 */
	public static EmployeeProject findEPByEmployeeIdAndProjectId(String employeeId,
			String projectId) {
		EmployeeProjectDao epd = new EmployeeProjectDao();
		return epd.findEPByEmployeeIdAndProjectId(employeeId,projectId);
	}
	/**
	 * 获得增加的消息
	 * @param num
	 * @return
	 */
	public static List<Message> getAddMsg(int num) {
		MessageDao md = new MessageDao();
		return listReverse(md.getAddMsg(num));
	}
	private static List<Message> listReverse(List<Message> list) {
		List<Message> messageList = new ArrayList<Message>();
		Message m = null;
		for(int i = list.size()- 1; i >= 0 ; i-- ) {
			m = list.get(i);
			messageList.add(m);
		}
		return messageList;
	}
}
